<?php
namespace Home\Controller;

class SystemController extends BaseController
{

    /**
     * @deprecated
     */
    public function uploadhandle($action = '')
    {
        $this->upload_handle($action);
    }

    public function upload_handle($action = '')
    {
        // 上传说明：
        // 考虑到未来存储，上传的临时数据在_RUN/Temp（TEMP_PATH=./_RUN/Temp）
        // 添加成功后，所有数据传送到 data/*中
        // 注意data/中的所有数据都应该使用Storage驱动来操作，方便后期移植
        $config = array(

            // 删除用户的文件
            'deleteActionName' => 'deletefile',

            // 上传图片配置项
            'imageActionName' => 'uploadimage',
            'imageFieldName' => 'upfile',
            'imageMaxSize' => C('USER_UPLOAD.IMAGE_MAX_SIZE'),
            'imageAllowFiles' => C('USER_UPLOAD.IMAGE_ALLOW_EXT'),
            'imageCompressEnable' => true,
            'imageCompressBorder' => 1600,
            'imageInsertAlign' => 'none',
            'imageUrlPrefix' => __ROOT__ . '/',

            // 涂鸦图片上传配置项
            'scrawlActionName' => 'uploadscrawl',
            'scrawlFieldName' => 'upfile',
            'scrawlMaxSize' => C('USER_UPLOAD.SCRAWL_MAX_SIZE'),
            'scrawlUrlPrefix' => __ROOT__ . '/',
            'scrawlInsertAlign' => 'none',

            // 截图工具上传，IE可以使用
            'snapscreenActionName' => 'uploadimage',
            'snapscreenUrlPrefix' => __ROOT__ . '/',
            'snapscreenInsertAlign' => 'none',

            // 抓取远程图片配置
            'catcherLocalDomain' => array(), // 忽略的域名 img.baidu.com
            'catcherActionName' => 'catchimage',
            'catcherFieldName' => 'source',
            'catcherUrlPrefix' => __ROOT__ . '/',
            'catcherMaxSize' => C('USER_UPLOAD.CATCHER_MAX_SIZE'),
            'catcherAllowFiles' => C('USER_UPLOAD.CATCHER_ALLOW_EXT'),

            // 上传视频配置
            'videoActionName' => 'uploadvideo',
            'videoFieldName' => 'upfile',
            'videoUrlPrefix' => __ROOT__ . '/',
            'videoMaxSize' => C('USER_UPLOAD.VIDEO_MAX_SIZE'),
            'videoAllowFiles' => C('USER_UPLOAD.VIDEO_ALLOW_EXT'),

            // 上传文件配置
            'fileActionName' => 'uploadfile',
            'fileFieldName' => 'upfile',
            'fileUrlPrefix' => __ROOT__ . '/',
            'fileMaxSize' => C('USER_UPLOAD.FILE_MAX_SIZE'),
            'fileAllowFiles' => C('USER_UPLOAD.FILE_ALLOW_EXT'),

            // 列出指定目录下的图片
            'imageManagerActionName' => 'listimage',
            'imageManagerUrlPrefix' => __ROOT__ . '/',
            'imageManagerUrlPrefixPreview' => __ROOT__ . '/',
            'imageManagerListSize' => 20,
            'imageManagerInsertAlign' => 'none',
            'imageManagerAllowFiles' => C('USER_UPLOAD.IMAGE_LIST_EXT'),

            // 列出指定目录下的文件
            'fileManagerActionName' => 'listfile',
            'fileManagerUrlPrefix' => __ROOT__ . '/',
            'fileManagerUrlPrefixPreview' => __ROOT__ . '/',
            'fileManagerListSize' => 20,
            'fileManagerAllowFiles' => C('USER_UPLOAD.FILE_LIST_EXT')
        );

        if ('config' == $action) {
            $this->ajaxReturn($config);
        } else {
            $ret = array(
                'state' => '',
                'url' => '',
                'title' => '',
                'original' => '',
                'type' => '',
                'size' => 0
            );

            if (!MEMBER_LOGINED) {
                $ret['state'] = '您还没有登陆';
                $this->ajaxReturn($ret);
            }

            $up = new \Think\Upload ();
            $up->saveName = upload_temp_file_get();
            $up->replace = true;
            $up->subName = '';
            $up->rootPath = upload_temp_dir_get();

            if (!file_exists($up->rootPath)) {
                @mkdir($up->rootPath, 0777, true);
            }


            $upload_size_space = $this->_am->get('upload_space.space', 0);
            $one = D('MemberUpload')->table('__MEMBER_UPLOAD__ mu')->join('__DATA_FILES__ df ON df.id=mu.data_id')
                ->field('sum(df.filesize) as total')->where(array('mu.uid' => MEMBER_LOGINED_UID))->find();
            $upload_size_current = $one['total'];


            switch ($action) {
                case 'deletefile':
                    $files = I('post.files', '', array());
                    if (is_array($files)) {
                        foreach ($files as &$f) {
                            // /data/xxx
                            $f = preg_replace('/.*?(data\\/[a-z]+\\/\\d+\\/\\d+\\/\\d+_.+)$/', '\\1', $f);
                            $info = query_storage_file_by_fullpath($f);
                            if (!empty($info)) {
                                $exists = D('MemberUpload')->where(array('uid' => MEMBER_LOGINED_UID, 'data_id' => $info['id']))->find();
                                if (!empty($exists)) {
                                    D('MemberUpload')->delete($exists['id']);
                                    safe_delete_storage_file($f);
                                }
                            }
                        }
                        $ret['state'] = 'SUCCESS';
                    }
                    break;
                case 'listfile' :
                case 'listimage' :
                    $mapping = array(
                        'listfile' => 'file',
                        'listimage' => 'image'
                    );

                    $sret = (array(
                        "state" => "no match file",
                        "list" => array(),
                        "start" => 0,
                        "total" => 0,
                        'space' => byte_format($upload_size_current) . '/' . byte_format($upload_size_space)
                    ));

                    $size = I('get.size', 10, 'intval');
                    $start = I('get.start', 0, 'intval');

                    $list = array();
                    $where = array(
                        'df.dir' => $mapping [$action],
                        'mu.uid' => MEMBER_LOGINED_UID
                    );
                    $m = D('MemberUpload');
                    $total = $m->table('__MEMBER_UPLOAD__ mu')->join('__DATA_FILES__ df ON mu.data_id=df.id')->where($where)->field('COUNT(*) as total')->find();
                    $total = intval($total ['total']);
                    if ($total) {
                        foreach ($m->table('__MEMBER_UPLOAD__ mu')->join('__DATA_FILES__ df ON mu.data_id=df.id')->field('df.dir,df.path,df.uptime')->where($where)->limit($start, $size)->order('df.uptime DESC')->select() as $f) {
                            $list [] = array(
                                'url' => 'data/' . $f ['dir'] . '/' . $f ['path'],
                                'mtime' => $f ['uptime']
                            );
                        }

                        $sret = array(
                            "state" => "SUCCESS",
                            "list" => $list,
                            "start" => $start,
                            "total" => $total,
                            'space' => byte_format($upload_size_current) . '/' . byte_format($upload_size_space)
                        );
                    }

                    $this->ajaxReturn($sret);

                    break;
                case 'catchimage' :

                    if (false) {
                        set_time_limit(0);
                        $sret = array(
                            'state' => '',
                            'list' => null
                        );
                        $savelist = array();
                        $flist = I('request.' . $config ['catcherFieldName']);
                        if (empty ($flist)) {
                            $sret ['state'] = 'ERROR';
                        } else {
                            $sret ['state'] = 'SUCCESS';
                            foreach ($flist as $f) {
                                if (preg_match('/^(http|ftp|https):\\/\\//i', $f)) {

                                    $ext = strtolower(pathinfo($f, PATHINFO_EXTENSION));
                                    if (in_array('.' . $ext, $config ['catcherAllowFiles'])) {
                                        if ($img = file_get_contents($f)) {
                                            $savepath = save_storage_content('image', $ext, $img);
                                            if ($savepath) {
                                                $savelist [] = array(
                                                    'state' => 'SUCCESS',
                                                    'url' => 'data/image/' . $savepath,
                                                    'size' => strlen($img),
                                                    'title' => '',
                                                    'original' => '',
                                                    'source' => htmlspecialchars($f)
                                                );
                                            } else {
                                                $ret ['state'] = 'Save remote file error!';
                                            }
                                        } else {
                                            $ret ['state'] = 'Get remote file error';
                                        }
                                    } else {
                                        $ret ['state'] = 'File ext not allowed';
                                    }
                                } else {
                                    $savelist [] = array(
                                        'state' => 'not remote image',
                                        'url' => '',
                                        'size' => '',
                                        'title' => '',
                                        'original' => '',
                                        'source' => htmlspecialchars($f)
                                    );
                                }
                            }
                            $sret ['list'] = $savelist;
                        }
                        $this->ajaxReturn($sret);
                    }
                    break;
                case 'uploadscrawl' :

                    $data = I('post.' . $config ['scrawlFieldName']);
                    if (empty ($data)) {
                        $ret ['state'] = 'Scrawl Data Empty!';
                    } else {
                        $data = preg_replace('/^data:image\\/png;base64,/i', '', $data);
                        $img = base64_decode($data);
                        $savepath = save_storage_content('image', 'png', $img);
                        if ($savepath) {
                            $ret ['state'] = 'SUCCESS';
                            $ret ['url'] = 'data/image/' . $savepath;
                            $ret ['title'] = '';
                            $ret ['original'] = '';
                            $ret ['type'] = 'png';
                            $ret ['size'] = strlen($img);
                        } else {
                            $ret ['state'] = 'Save scrawl file error!';
                        }
                    }

                    break;
                case 'uploadfile' :
                case 'uploadimage' :
                case 'uploadvideo' :

                    if ($upload_size_current < $upload_size_space) {
                        $mapping = array(
                            'uploadfile' => 'file',
                            'uploadimage' => 'image',
                            'uploadvideo' => 'video'
                        );

                        $up->maxSize = $config [$mapping [$action] . 'MaxSize'];
                        foreach ($config [$mapping [$action] . 'AllowFiles'] as &$i) {
                            $i = trim($i, '.');
                        }
                        $up->exts = $config [$mapping [$action] . 'AllowFiles'];


                        if (!($info = $up->upload())) {
                            $ret ['state'] = $up->getError();
                        } else {

                            $one = &$info [$config [$mapping [$action] . 'FieldName']];
                            $savefile = upload_tempfile_save_storage($mapping [$action], $up->rootPath . $one ['savepath'] . $one ['savename'], $one['name']);

                            $ret ['state'] = 'SUCCESS';
                            $ret ['url'] = 'data/' . $mapping [$action] . '/' . $savefile;
                            $ret ['title'] = $one ['name'];
                            $ret ['original'] = $one ['name'];
                            $ret ['type'] = $one ['ext'];
                            $ret ['size'] = $one ['size'];

                            $file = query_storage_file($mapping[$action], $savefile);
                            if (!empty($file)) {
                                D('MemberUpload')->add(array(
                                    'data_id' => $file['id'],
                                    'uid' => MEMBER_LOGINED_UID
                                ));
                            } else {
                                $ret['state'] = '保存到用户数据库失败';
                            }

                        }
                    } else {
                        $ret['state'] = '最多有' . byte_format($upload_size_space) . '空间';
                    }
                    break;

                case 'uploadbutton' :
                case 'upload_button' :

                    // 注意，上传的文件需要进一步处理，目前只是在临时文件夹中
                    $mapping = array(
                        'image' => 'image',
                        'file' => 'file'
                    );
                    $type = I('get.type');

                    $value_holder = I('post.value_holder');
                    $preview_holder = I('post.preview_holder');
                    $upload_id = I('post.upload_id');
                    $show_alert = I('post.show_alert', 0, 'intval');

                    $up->maxSize = $config [$mapping [$type] . 'MaxSize'];
                    foreach ($config [$mapping [$type] . 'AllowFiles'] as &$i) {
                        $i = trim($i, '.');
                    }
                    $up->exts = $config [$mapping [$type] . 'AllowFiles'];


                    if (!($info = $up->upload())) {
                        $this->show('
<script type="text/javascript">
var win = window.parent.parent ;
win.$.dialog.alert("' . $up->getError() . '");
if(win._T_UPLOAD_BUTTON_WAITING.' . $upload_id . '){
	win._T_UPLOAD_BUTTON_WAITING.' . $upload_id . '.close();
	win._T_UPLOAD_BUTTON_WAITING.' . $upload_id . '=null;
}
</script>');
                    } else {
                        $one = &$info ['value_file'];
                        $savefile = $up->rootPath . $one ['savepath'] . $one ['savename'];

                        $this->show('
<script type="text/javascript">
var win = window.parent.parent ;
win.$("' . $value_holder . '",window.parent.parent.document.body).val("' . $savefile . '");
win.$("' . $preview_holder . '",window.parent.parent.document.body).attr("src","' . __ROOT__ . '/' . $savefile . '");
win.$("' . $preview_holder . '",window.parent.parent.document.body).prop("href","' . __ROOT__ . '/' . $savefile . '");
win.$("' . $preview_holder . '",window.parent.parent.document.body).show();
' . ($show_alert ? 'win.$.dialog.alert("' . L('upload_success') . '!");' : '') . '
if(win._T_UPLOAD_BUTTON_WAITING.' . $upload_id . '){
	win._T_UPLOAD_BUTTON_WAITING.' . $upload_id . '.close();
	win._T_UPLOAD_BUTTON_WAITING.' . $upload_id . '=null;
}
if(win._T_UPLOAD_BUTTON_CALLBACK.' . $upload_id . '){
	win._T_UPLOAD_BUTTON_CALLBACK.' . $upload_id . '("' . $savefile . '");
};
</script>');
                    }
                    return;
                    break;
            }
            $this->ajaxReturn($ret);
        }
    }
}